package com.start.shop.api.controller;

import java.util.Date;


import javax.validation.Valid;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.start.shop.api.param.user.LoginParam;
import com.start.shop.api.vo.user.LoginVo;
import com.start.shop.common.constant.MsgObject;
import com.start.shop.common.util.RedisService;
import com.start.shop.common.weixin.WxUserUtil;
import com.start.shop.common.weixin.domain.WxUserInfo;
import com.start.shop.modules.repository.entity.User;
import com.start.shop.modules.service.IUserService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping(value = "/api")
public class UserController {

	@Autowired
	IUserService userService;
	
	@Autowired
	WxUserUtil wxUserUtil;
	
	@Autowired
	RedisService redisService;
	
	@RequestMapping(value = "/login")
	public ResponseEntity<MsgObject> login(@RequestBody @Valid LoginParam loginParam) {
		
		//登录验证：根据code获取session和 key
		WxUserInfo wxUserInfo = wxUserUtil.code2UserInfo(loginParam.getCode(), loginParam.getEncryptData(),
				loginParam.getData(), loginParam.getSign(), loginParam.getIv());
		
		User user = userService.getUserByOpenId(wxUserInfo.getOpenId());
		//如果存在，直接返回session，不存在插入到user表中再返回session
		if(user == null ) {
			user = User.setData(wxUserInfo);
			//首次注册
			userService.insert(user);
			user = userService.getUserByOpenId(wxUserInfo.getOpenId());
			//推送首次注册事件
		}
		//产生客户端session sha1(user.toString)
		String sessionStr = user.toString() + new Date().getTime();
		String token =String.format("%08d", user.getUserId()) + DigestUtils.sha1Hex(sessionStr.getBytes()).toString();
		
		//将user信息放置到redis中
		user.setToken(token);
	    redisService.set(String.format("%08d", user.getUserId()), user);
	    
	    LoginVo loginVo = new LoginVo(token, "1234567890abcdef");
		
		return ResponseEntity.ok(MsgObject.success(loginVo));
	}
}
